package cn.codeforfun.vote;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

/**
 * Created by Administrator on 2017/2/17 0017.
 */
@Repository
public class VoteDaoImpl implements VoteDaoCustom {
    @Autowired
    private EntityManager entityManager;

    @Override
    public Page<Vote> findAllPage(Pageable pageable) {
        Query query = entityManager.createQuery("select distinct v from Vote v left join fetch v.questions q left join fetch q.options o left join fetch o.users");
        List resultList = query.setMaxResults(pageable.getPageSize()).setFirstResult((pageable.getPageNumber()) * pageable.getPageSize()).getResultList();
        long resultCount = (long) entityManager.createQuery("select count(v.id) from Vote v").getSingleResult();
        return new PageImpl(resultList, pageable, resultCount);
    }

    @Override
    public Vote findVoteWithSubject(Long id) {
        Query query = entityManager.createQuery(
                "select distinct v from Vote v " +
                        "left join fetch v.questions q " +
                        "left join fetch q.options o " +
                        "left join fetch o.followerOptions fo " +
                        "left join fetch fo.follower f " +
                        "where v.id=:id").setParameter("id", id);
        Vote vote = (Vote) query.getSingleResult();
        return vote;
    }

    @Override
    public List<Vote> findVoteWithSubject() {
        Query query = entityManager.createQuery(
                "select distinct v from Vote v " +
                        "left join fetch v.questions q " +
                        "left join fetch q.options o " +
                        "left join fetch o.followerOptions fo " +
                        "left join fetch fo.follower f " +
                        "left join fetch v.material m " +
                        "left join fetch v.prizes p ");
        List<Vote> resultList = query.getResultList();
        return resultList;
    }

    @Override
    public Vote findOneWithPrize(Long id) {
        Query q = entityManager.createQuery("select distinct v from Vote v " +
                "left join fetch v.prizes p " +
                "where v.id=:id").setParameter("id", id);
        Vote vote = (Vote) q.getSingleResult();
        return vote;
    }

    @Override
    public Vote findWithMaterial(Long voteId) {
        Query q = entityManager.createQuery("select distinct v from Vote v " +
                "left join fetch v.material m where v.id=:id").setParameter("id", voteId);
        Vote vote = (Vote) q.getSingleResult();
        return vote;
    }
}
